package secondriver.heathfood.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.widget.AdapterView;
import butterknife.Bind;
import butterknife.ButterKnife;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import secondriver.heathfood.R;
import secondriver.heathfood.adapter.FoodBriefListAdapter;
import secondriver.heathfood.client.ApiClient;
import secondriver.heathfood.client.Constants;
import secondriver.heathfood.bean.FoodDetail;
import secondriver.heathfood.bean.PageParams;
import secondriver.heathfood.common.*;
import secondriver.heathfood.util.LogUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Author : secondriver
 */
public class FoodBriefActivity extends AbstractBaseActivity {

    private static final LogUtil logUtil = LogUtil.getLogger(FoodBriefActivity.class.getName());

    static final int LoadingWhat = 0x01;
    static final int DialogWhat = 0x10;

    @Bind(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @Bind(R.id.food_detail_ListView)
    SwipeMenuListView mListView;

    private FoodBriefListAdapter mAdapter;
    private List<FoodDetail> foodDetailList = new ArrayList<>();

    private final PageParams mPageParams = new PageParams();

    private Handler mHandler;
    private ApiClient mApiClient;

    private ProgressDialog progressDialog;
    private int progressMax = 100;
    private int progress = 10;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_food_brief);
        ButterKnife.bind(this);
        setActionBarTitle(R.string.heath_food_brief);

        initVariable();
        initHandler();
        initListener();
        initLoadData();
    }

    private void initVariable() {
        if (mApiClient == null) {
            mApiClient = ApiClient.build(this, Constants.FOOD_DETAIL_CACHE_NAME);
        }
        if (mAdapter == null) {
            mAdapter = new FoodBriefListAdapter(this, foodDetailList, mApiClient.getSimpleDiskCache());
        }
        mPageParams.page = 6;
    }

    private void initHandler() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(getResources().getString(R.string.info_food_loading));
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMax(progressMax);

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case LoadingWhat:
                        if (progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        foodDetailList.clear();
                        foodDetailList.addAll((List<FoodDetail>) msg.obj);
                        mListView.setAdapter(mAdapter);
                        mAdapter.notifyDataSetChanged();
                        mSwipeRefreshLayout.setRefreshing(false);
                        break;
                    case DialogWhat:
                        if (progress >= progressMax) {
                            progress = 0;
                            progressDialog.setProgress(progress);
                        } else {
                            progress++;
                            progressDialog.incrementProgressBy(1);
                        }
                        sendEmptyMessageDelayed(DialogWhat, 10);
                        break;
                    default:
                        break;
                }
            }
        };

        progressDialog.show();
        progress = progress > 0 ? progress : 0;
        progressDialog.setProgress(progress);
        mHandler.sendEmptyMessageDelayed(DialogWhat, 10);
    }

    private void initListener() {

        mSwipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_dark, android.R.color.holo_orange_dark
                , android.R.color.holo_green_dark);
//        mSwipeRefreshLayout.setProgressViewOffset(true, dp2px(150), dp2px(250));
//        mSwipeRefreshLayout.setProgressViewEndTarget(true, dp2px(150));

        //SwipeRefresh Refresh Listener
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPageParams.page += 1;
                mSwipeRefreshLayout.setRefreshing(true);
                backstageLoadData();
            }
        });

        // step 1. create a MenuCreator
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                // create "Favorite" item
                SwipeMenuItem favoriteItem = new SwipeMenuItem(
                        getApplicationContext());
                favoriteItem.setBackground(R.color.favorite_yellow);
                favoriteItem.setWidth(dp2px(90));
                favoriteItem.setIcon(R.drawable.ic_action_favorite);
                menu.addMenuItem(favoriteItem);

                // create "Share" item
                SwipeMenuItem shareItem = new SwipeMenuItem(
                        getApplicationContext());
                shareItem.setBackground(R.color.share_blue);
                shareItem.setWidth(dp2px(90));
                shareItem.setIcon(R.drawable.ic_action_share);
                menu.addMenuItem(shareItem);
            }
        };
        // set creator
        mListView.setMenuCreator(creator);

        // step 2. listener item click event
        mListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, final SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        //收藏
                        FoodDetail foodDetail = (FoodDetail) mAdapter.getItem(position);
                        FoodDetail.FoodDetailBuilder foodDetailBuilder = new FoodDetail.FoodDetailBuilder();

                        //SQLite方式收藏
                        long id =
                                sqliteHelper.insertOrUpdate(FoodDetail.MetaInfo.TABLE_NAME, foodDetailBuilder
                                        .builderToContentValues
                                                (foodDetail), " f_id=?", String.valueOf(foodDetail.getId()));
                        logUtil.info("Favorite foodDetail rs  id = %d", id);
                        if (id == 0) {
                            showSimpleToast(R.string.info_favorite_already);
                        } else if (id == -1) {
                            showSimpleToast(R.string.info_favorite_failed);
                        } else {
                            showSimpleToast(R.string.info_favorite_succeed);
                        }

                        //KVCache方式收藏
//                        final int menuIndex = index;
//                        sqLiteCache.put(String.valueOf(foodDetail.getId()), ApiClient.FoodDetailConvertJson(foodDetail), new
//                                SimpleSQLiteCache
//                                        .PutListener() {
//                                    @Override
//                                    public void onPutCallback(boolean state, boolean insertOrUpdate, SimpleSQLiteCache.KVCacheItem KVCacheItem) {
//                                        if (state) {
//                                            showSimpleToast(R.string.info_favorite_succeed);
//                                            menu.getMenuItem(menuIndex).setBackground(R.color.red);
//                                        } else {
//                                            showSimpleToast(R.string.info_favorite_failed);
//                                        }
//                                    }
//                                });
                        break;
                    case 1:
                        //分享
                        showSimpleToast("分享到微信");
                        break;
                    default:
                }
            }
        });

        // set SwipeListener
        mListView.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

            @Override
            public void onSwipeStart(int position) {
                // swipe start
            }

            @Override
            public void onSwipeEnd(int position) {
                // swipe end
            }
        });

        // other setting
        mListView.setCloseInterpolator(new BounceInterpolator());

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(FoodBriefActivity.this, FoodDetailActivity.class);
//                boolean exist = sqLiteCache.exist(String.valueOf(id));
                intent.putExtra(Constants.FOOD_ID, id);
                startActivity(intent);
            }
        });
    }

    private void initLoadData() {
        Intent intent = getIntent();
        mPageParams.cid = intent.getIntExtra(Constants.CLASSIFY_ID, Constants.DEFAULT_CID);
        backstageLoadData();
    }


    private void backstageLoadData() {
        final Message message = Message.obtain(mHandler);
        message.what = LoadingWhat;
        final Bundle bundle = new Bundle();
        bundle.putParcelable(Constants.FOOD_LIST, mPageParams);
        BackgroundTaskExecutor.doTask(bundle, message, new BackgroundTasks.LoadFoodBrief(mApiClient));
    }

}
